<?php 
namespace Admin\Controller;
use Think\Controller;
use Think\Auth;
class CommonController extends Controller {
	function _initialize() {
		$this->checkSessionIdle();
		//如果没有登录，或登录超时，直接跳转
        if(is_adm_login() == 0){ 
        	redirect(PHP_FILE . C('USER_AUTH_GATEWAY'));
       	} 
        // 用户权限检查
        if (!in_array(MODULE_NAME.'/'.CONTROLLER_NAME.'/'.ACTION_NAME, explode(',', C('NOT_AUTH_MODULE')))) { 
          $result = false;
	        if(session('uid')==1 && session('username')=='admin'){
	          $result = true;
	        }else{
	           //下面代码动态判断权限
  				  $auth=new Auth();
  				  $result=$auth->check(MODULE_NAME.'/'.CONTROLLER_NAME.'/'.ACTION_NAME,session('uid'));			
	        }
        	if(!$result){
				      $this->error('没有权限');
			    }
		}
    }
    //检查是否登录超时
    public function checkSessionIdle()
    {
        if(time() <= session('idle')){
            session('idle', time()+C('SESSION_IDLE'));
        }elseif(!(session('idle'))){
			redirect(PHP_FILE . C('USER_AUTH_GATEWAY'));
		}else{
        	session_unset();
            session('[destroy]');
           	$data['status']=-1;
		 	$data['info']='登录超时，请重新登陆';
            $this->ajaxReturn($data,'json');
        }
    }

	//修改用户状态->停止
	public function dStatus(){
		$id = $_GET['id'];
		$db=M(CONTROLLER_NAME);
		if(isset($id)){
			if (M(CONTROLLER_NAME)->where(array('id'=>$id))->setField('status',0)) {
                    $this->success ('修改成功');
                } else {
                    $this->error ('修改失败');
            }
		}
	}
	//修改状态->启用
	public function sStatus(){
		$id = $_GET['id'];
		if(isset($id)){
			if (M(CONTROLLER_NAME)->where(array('id'=>$id))->setField('status',1)) {
                    $this->success ('修改成功');
                } else {
                    $this->error ('修改失败');
            }
		}
	}
	//删除信息
	public function del(){
		$id = $_GET['id'];
		if(isset($id)){
			if (M(CONTROLLER_NAME)->delete ($id)) {
                    $this->success ('删除成功！');
                } else {
                    $this->error ('删除失败！');
            }
		}
	}
	//将记录由正常状态改为删除状态
	public function delete(){
		$id = $_GET['id'];
		if(isset($id)){
			if (M(CONTROLLER_NAME)->where(array('id'=>$id))->setField('del',1)) {
                    $this->success ('删除成功');
                } else {
                    $this->error ('删除失败');
            }
		}
	}
	//将记录由删除状态改为正常状态
	public function regain(){
		$id = $_GET['id'];
		if(isset($id)){
			if (M(CONTROLLER_NAME)->where(array('id'=>$id))->setField('del',0)) {
                    $this->success ('恢复成功');
                } else {
                    $this->error ('恢复失败');
            }
		}

	}
    //公用的列表页查询方法
    protected function _search(){
        if($_POST['search_where']){
            $where=array();
            foreach($_POST['search_where'] as $key=>$val){
                foreach($val as $k=>$v){
                   if($v=='') continue;//if(!$v)这样写法如果值为0不行
                   if($k=='like'){
                       $where[$key]=array($k,'%'.$v.'%');
                   }elseif($k=='exp'){
                       $v=explode('-',$v);
                       $where[$key]=array($v[0],(int)$v[1]);
                   }elseif($k=='and'||$k=='or'){
                       foreach($v as $k2=>$v2){
                           if($v2=='') continue;
                           if($k2=='gt_date'){
                               $where[$key][]=array('egt',strtotime($v2));
                           }elseif($k2=='lt_date'){
                               $where[$key][]=array('elt',strtotime("$v2 +1 day"));
                           }else{
                               $where[$key][]=array($k2,$v2);
                           }
                       }
                       if($where[$key]) $where[$key][]=$k;
                   }else{
                   		if($key=='date'){
                   			//如果为时间的话，转换层时间戳
                   			$where[$key]=array($k,strtotime($v));
                   		}else{
                       		$where[$key]=array($k,$v);
                       	}
                   }
                }
            } 
         
        	// $this->search_where = array_merge($this->search_where,$where);
        	// $_SESSION['search_where'] = $this->search_where;
        	// $this->search_value = array_merge($this->search_value,$_POST['search_where']);
        	// $_SESSION['search_value'] = $this->search_value;
        	return $where;

        }
    }
    /**
     * 共用添加新记录
     */
  public function add(){
		if(!empty($_POST)){
			$db=D(CONTROLLER_NAME);
      if (!$db->create()){
        $this->error($db->getError());
      }else{
        $db->add();
        $this->success('添加成功');
      }
    }else{
      $this->display();
    } 
	}
	/**
	 * 共用编辑记录
	 */
	public function edit(){
		if(!empty($_POST)){
			$db=D(CONTROLLER_NAME);
      if(!$db->create()) {
        $this->error($db->getError());
      }else{
        // 修改帐号数据
        if($result=$db->save()) {
          $this->success('更新成功!');
        }else{
          $this->error('更新成功!');
        }
      }
		}else{
			$id=$_GET['id'];
			$db=M(CONTROLLER_NAME);
			$this->list=$db->find($id);
			$this->display();
		}
	}
  
  //权限库房及供应商加载
  public function search(){
      $where['del']=array('eq','0');
      $depots=session('depots');
      $where['id']=array('in',$depots);
      $db=M('depot');
      $this->depot=$db->where($where)->field(array('id','name'))->select();
      $db1=M('supplier');
      $this->supplier=$db1->where(array('del'=>array('eq','0')))->field(array('id','name'))->select();
  }

	//空方法
	public function _empty()
    {
        redirect(U(MODULE_NAME.'/'.CONTROLLER_NAME.'/index'));
    }
    
    //修改状态->状态确认 status更改为2
  public function statusConfirm(){
    $id = $_GET['id'];
    if(isset($id)){
      if (M(CONTROLLER_NAME)->where(array('id'=>$id))->setField('status',2)) {
          $this->success ('修改成功');
        } else {
          $this->error ('修改失败');
        }
    }
  }
  //修改状态->状态确认 status更改为2--批量
  public function statusConfirms(){
    $ids=$_POST['ids'];
    if(isset($ids)){
      if (M(CONTROLLER_NAME)->where(array('id'=>array('in',$ids)))->setField('status',2)) {
          $this->success ('修改成功');
        } else {
          $this->error ('修改失败');
        }
    }
  }
  public function getExcel($fileName,$headArr,$data){
    //对数据进行检验
      if(empty($data) || !is_array($data)){
          die("data must be a array");
      }
      //检查文件名
      if(empty($fileName)){
          exit;
      }
      $date = date("Y_m_d",time());
      $fileName .= "_{$date}.xls";
    //创建PHPExcel对象，注意，不能少了\
      $objPHPExcel = new \PHPExcel();
      $objProps = $objPHPExcel->getProperties();
      //设置表头
      $key = ord("A");
      foreach($headArr as $v){
          $colum = chr($key);
          $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum.'1', $v);
          $key += 1;
      }
      
      $column = 2;
      $objActSheet = $objPHPExcel->getActiveSheet();
      foreach($data as $key => $rows){ //行写入
          $span = ord("A");
          foreach($rows as $keyName=>$value){// 列写入
              $j = chr($span);
              $objActSheet->setCellValue($j.$column, $value);
              $span++;
          }
          $column++;
    }

      $fileName = iconv("utf-8", "gb2312", $fileName);
      //重命名表
      // $objPHPExcel->getActiveSheet()->setTitle('test');
      //设置活动单指数到第一个表,所以Excel打开这是第一个表
      $objPHPExcel->setActiveSheetIndex(0);
      header('Content-Type: application/vnd.ms-excel');
    header("Content-Disposition: attachment;filename=\"$fileName\"");
    header('Cache-Control: max-age=0');

      $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
      $objWriter->save('php://output'); //文件通过浏览器下载
      exit;
  }
  
}